package com.aw.guiguzi.widgets

import android.app.Activity
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Switch
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aw.baselib.base.AwBaseConstant
import com.aw.baselib.util.AwDisplayUtil
import com.aw.baselib.util.AwPopupwindowUtil
import com.aw.baselib.util.AwRecyclerViewUtil
import com.aw.baselib.util.AwToastUtil
import com.aw.guiguzi.R
import com.aw.guiguzi.bean.CalSuggestItemBean
import com.aw.guiguzi.bean.NumHandleInputResultBean
import com.aw.guiguzi.event.EventRefreshCalResultType
import com.aw.guiguzi.listeners.OnCommonCheckedListener
import com.aw.guiguzi.module.setting.adapter.SettingUiSuggestAdapter
import com.aw.guiguzi.util.AppCacheUtil
import com.aw.guiguzi.util.CommonUtil.isAllow
import com.aw.guiguzi.util.CommonUtil.setOnCheckedChangeListener
import com.aw.guiguzi.util.DataUtil.allTrendList
import org.greenrobot.eventbus.EventBus

class MainCalAnalaysisPopupWindow(
    private val mActivity: Activity,
    dismissListener: OnDismissListener?
) : PopupWindow() {
    private val contentView: View
    private val mAdapter: SettingUiSuggestAdapter
    private var mSuggestItemBeanList: MutableList<CalSuggestItemBean> = ArrayList()

    init {
        contentView = View.inflate(mActivity, R.layout.view_popupwindow_main_cal_analaysis, null)
        val rcv_data = contentView.findViewById<RecyclerView>(R.id.rcv_data)
        val iv_close = contentView.findViewById<ImageView>(R.id.iv_close)
        iv_close.setOnClickListener { v: View? -> dismiss() }
        val switch_typePercent = contentView.findViewById<Switch>(R.id.switch_typePercent)
        switch_typePercent.isChecked = AppCacheUtil.isUseTypePercent()
        val switch_trendsAutoFilter = contentView.findViewById<Switch>(R.id.switch_trendsAutoFilter)
        switch_trendsAutoFilter.isChecked = AppCacheUtil.isTrendsAutoFilter()
        val switch_jumpSmoothly = contentView.findViewById<Switch>(R.id.switch_jumpSmoothly)
        switch_jumpSmoothly.isChecked = AppCacheUtil.isJumpSmoothly()
        val rg_calInterval = contentView.findViewById<RadioGroup>(R.id.rg_calInterval)
        val rBtn_calInterval1 = contentView.findViewById<RadioButton>(R.id.rBtn_calInterval1)
        val rBtn_calInterval2 = contentView.findViewById<RadioButton>(R.id.rBtn_calInterval2)
        val rBtn_calInterval3 = contentView.findViewById<RadioButton>(R.id.rBtn_calInterval3)
        if (AppCacheUtil.getCalIntervalNum() == 1) {
            rBtn_calInterval1.isChecked = true
        } else if (AppCacheUtil.getCalIntervalNum() == 2) {
            rBtn_calInterval2.isChecked = true
        } else {
            rBtn_calInterval3.isChecked = true
        }
        rg_calInterval.setOnCheckedChangeListener { group: RadioGroup?, checkedId: Int ->
            if (!isAllow) {
                return@setOnCheckedChangeListener
            }
            when (checkedId) {
                R.id.rBtn_calInterval1 -> AppCacheUtil.setCalIntervalNum(1)
                R.id.rBtn_calInterval2 -> AppCacheUtil.setCalIntervalNum(2)
                R.id.rBtn_calInterval3 -> AppCacheUtil.setCalIntervalNum(3)
            }
            EventBus.getDefault().postSticky(EventRefreshCalResultType(null))
        }
        val tv_currentPercent = contentView.findViewById<TextView>(R.id.tv_currentPercent)
        tv_currentPercent.text = "当前：" + AppCacheUtil.getBetterTrendsPercent() + "%"
        val rg_betterTrendsPercent =
            contentView.findViewById<RadioGroup>(R.id.rg_betterTrendsPercent)
        val rBtn_percent60 = contentView.findViewById<RadioButton>(R.id.rBtn_percent60)
        val rBtn_percent70 = contentView.findViewById<RadioButton>(R.id.rBtn_percent70)
        val rBtn_percent75 = contentView.findViewById<RadioButton>(R.id.rBtn_percent75)
        val rBtn_percent80 = contentView.findViewById<RadioButton>(R.id.rBtn_percent80)
        val rBtn_percent85 = contentView.findViewById<RadioButton>(R.id.rBtn_percent85)
        val rBtn_percent90 = contentView.findViewById<RadioButton>(R.id.rBtn_percent90)
        val rBtn_percentCustom = contentView.findViewById<RadioButton>(R.id.rBtn_percentCustom)
        when (AppCacheUtil.getBetterTrendsPercent()) {
            60 -> rBtn_percent60.isChecked = true
            70 -> rBtn_percent70.isChecked = true
            75 -> rBtn_percent75.isChecked = true
            80 -> rBtn_percent80.isChecked = true
            85 -> rBtn_percent85.isChecked = true
            90 -> rBtn_percent90.isChecked = true
            else -> {
                rBtn_percent60.isChecked = false
                rBtn_percent70.isChecked = false
                rBtn_percent75.isChecked = false
                rBtn_percent80.isChecked = false
                rBtn_percent85.isChecked = false
                rBtn_percent90.isChecked = false
            }
        }
        rg_betterTrendsPercent.setOnCheckedChangeListener { group: RadioGroup?, checkedId: Int ->
            if (!isAllow) {
                return@setOnCheckedChangeListener
            }
            when (checkedId) {
                R.id.rBtn_percent60 -> AppCacheUtil.setBetterTrendsPercent(60)
                R.id.rBtn_percent70 -> AppCacheUtil.setBetterTrendsPercent(70)
                R.id.rBtn_percent75 -> AppCacheUtil.setBetterTrendsPercent(75)
                R.id.rBtn_percent80 -> AppCacheUtil.setBetterTrendsPercent(80)
                R.id.rBtn_percent85 -> AppCacheUtil.setBetterTrendsPercent(85)
                R.id.rBtn_percent90 -> AppCacheUtil.setBetterTrendsPercent(90)
                R.id.rBtn_percentCustom -> AppCacheUtil.setBetterTrendsPercent(AppCacheUtil.getBetterTrendsPercent())
            }
            tv_currentPercent.text = "当前：" + AppCacheUtil.getBetterTrendsPercent() + "%"
            EventBus.getDefault().postSticky(EventRefreshCalResultType(null))
        }
        mAdapter = SettingUiSuggestAdapter()
        AwRecyclerViewUtil.setRecyclerViewLinearlayout(mActivity, rcv_data, mAdapter, false)
        mSuggestItemBeanList = allTrendList
        mAdapter.addAllData(mSuggestItemBeanList)
        setOnCheckedChangeListener(switch_trendsAutoFilter, object : OnCommonCheckedListener {
            override fun callback(isChecked: Boolean) {
                if (isChecked) {
                    AppCacheUtil.setTrendsAutoFilter(true)
                    AwToastUtil.show("自定义走势智能展示已启用")
                } else {
                    AppCacheUtil.setTrendsAutoFilter(false)
                    AwToastUtil.show("自定义走势智能展示已关闭")
                }
                EventBus.getDefault().postSticky(EventRefreshCalResultType(null))
            }

        })
        setOnCheckedChangeListener(switch_typePercent, object : OnCommonCheckedListener {
            override fun callback(isChecked: Boolean) {
                if (isChecked) {
                    AppCacheUtil.setUseTypePercent(true)
                    AwToastUtil.show("分类百分比已启用")
                } else {
                    AppCacheUtil.setUseTypePercent(false)
                    AwToastUtil.show("分类百分比已关闭")
                }
                EventBus.getDefault().postSticky(EventRefreshCalResultType(null))
            }

        })
        setOnCheckedChangeListener(switch_typePercent, object : OnCommonCheckedListener {
            override fun callback(isChecked: Boolean) {
                if (isChecked) {
                    AppCacheUtil.setJumpSmoothly(true)
                    AwToastUtil.show("自定义走势分析已启用")
                    setCustomJumpSmoothly(true)
                    EventBus.getDefault().postSticky(EventRefreshCalResultType(null))
                } else {
                    if (!AppCacheUtil.isCommonAnalysis()) {
                        switch_jumpSmoothly.isChecked = true
                        AwToastUtil.show("通用走势与自定义走势至少存在一种")
                    } else {
                        AppCacheUtil.setJumpSmoothly(false)
                        AwToastUtil.show("自定义走势分析已禁用")
                        setCustomJumpSmoothly(false)
                        EventBus.getDefault().postSticky(EventRefreshCalResultType(null))
                    }
                }
            }

        })


        setContentView(contentView)
        this.width = ViewGroup.LayoutParams.MATCH_PARENT
        this.height = (AwDisplayUtil.deviceHeightPX(mActivity) * 0.9).toInt()
        this.animationStyle = com.aw.baselib.R.style.sytle_anim_pop_in_out
        this.isFocusable = true
        this.isTouchable = true
        this.isOutsideTouchable = true
        setBackgroundDrawable(BitmapDrawable())
        this.update()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.overlapAnchor = true
        }
        if (dismissListener == null) {
            setOnDismissListener {
                val lp = mActivity.window.attributes
                lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_NORMAL
                mActivity.window.attributes = lp
            }
        } else {
            setOnDismissListener(dismissListener)
        }
    }

    private fun setCustomJumpSmoothly(isOpen: Boolean) {
        for (itemBean in mSuggestItemBeanList) {
            itemBean.isEnable = isOpen
            AppCacheUtil.setTrendActive(itemBean.tag, isOpen)
        }
        mAdapter.addAllData(mSuggestItemBeanList)
    }

    /**
     * 展示窗口
     */
    fun show(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        this.showAsDropDown(parent, 0, 0)
    }

    fun showAsLocation(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationNoAlpha(parent: View?) {
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationBottom(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        showAtLocation(parent, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
    }

    /**
     * calendar菜单选择监听接口
     */
    interface OnResultCallback {
        fun onResult(bean: NumHandleInputResultBean?)
    }
}